package cn.edu.zust.se.service.share.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.edu.zust.se.api.entity.ShareLink;
import cn.edu.zust.se.api.entity.bo.ShareLinkBo;
import cn.edu.zust.se.api.entity.vo.ShareLinkVo;
import cn.edu.zust.se.service.share.mapper.ShareLinkMapper;
import cn.edu.zust.se.service.share.service.ShareLinkService;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@RequiredArgsConstructor
public class ShareLinkServiceImpl extends ServiceImpl<ShareLinkMapper, ShareLink> implements ShareLinkService {
    private final ShareLinkMapper shareLinkMapper;

    @Override
    public Boolean createShareLink(ShareLinkBo bo) {
        ShareLink shareLink = BeanUtil.copyProperties(bo, ShareLink.class);
        shareLink.setUserId(Long.parseLong((String) StpUtil.getLoginId()));
        return baseMapper.insert(shareLink) > 0;
    }

    @Override
    public Boolean checkShareLink(ShareLinkBo bo) {
        ShareLink shareLink = baseMapper.selectById(bo.getId());
        if (shareLink == null) {
            return false;
        }
        if (shareLink.getExpirationTime().before(new Date())) {
            return false;
        }
        return shareLink.getCode().equals(bo.getCode());
    }

    @Override
    public ShareLinkVo getShareLink(String path) {
        LambdaQueryWrapper<ShareLink> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShareLink::getPath, path);
        ShareLink shareLink = shareLinkMapper.selectOne(wrapper);
        if (shareLink != null) {
            ShareLinkVo shareLinkVo = BeanUtil.copyProperties(shareLink, ShareLinkVo.class);
            return shareLinkVo;
        }
        return null;
    }
}
